<template>
    <div id="irp-domain" style="max-width: 800px;">
    <div class="bi-toolbar bi-bg-white">
        <el-row>
            <el-button type="button" class="bi-el-btn" @click="saveDomain" :disabled="updateFlag < 2">保存</el-button>
        </el-row>
    </div>
     <el-divider></el-divider>
    <div class="bi-ui-dialog-content">
        <el-form ref="folderItem" class="bi-el-form" :model="folderItem" :rules="rules" label-width="80px">
            <el-form-item label="标识" prop="name" >
                <el-input ref="focus_input_domain" class="input-toupper" v-model="folderItem.name" placeholder="请输入标识" :disabled="codeTitleReadOnly"></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input v-model="folderItem.title" placeholder="请输入标题" :disabled="codeTitleReadOnly"></el-input>
            </el-form-item>
            <el-form-item label="布局方案" prop="lysGuid">
                <el-select v-model="folderItem.lysGuid" placeholder="请选择布局方案" popper-class="bi-el-select-panel irp-domain_lys-popper">
                    <el-option v-for="item in lysItems" :key="item.guid" :label="item.title" :value="item.guid"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="labels">
                <el-select placeholder="请选择标签" v-model="labelNames" multiple popper-class="bi-el-select-panel irp-domain_labels-popper" @change="tagSelectChange">
                    <el-option class="bi-el-select-panel-tree" :label="folderItem.empty" :value="folderItem.empty">
                        <el-tree
                                :indent=24
                                node-key="id"
                                ref="applabelTree"
                                show-checkbox
                                :data="labelTree"
                                :highlight-current="true"
                                :check-on-click-node="true"
                                :expand-on-click-node="false"
                                :default-checked-keys="folderItem.labels"
                                @check-change="handleCheckChange"
                                class="bi-el-tree bi-el-tree-dropdown">
                        </el-tree>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="说明" prop="desc">
                <el-input type="textarea" v-model="folderItem.desc" placeholder="请输入说明" maxlength="165" :autosize="{minRows:5,maxRows:5}"></el-input>
            </el-form-item>
        </el-form>
    </div>
    </div>
</template>

<script>
import { folderApi, layoutApi } from "@/api/irpApi.js";

export default {
    props: {
        currNodeId: {
            type: String,
            required:true,
        },
        codeTitleReadOnly: {
            type: Boolean,
            required:true,
            default:false
        }
    },
    data() {
        return {
            folderItem: {},         // 域、应用系统项
            labelTree: [],          // 标签库树形列表
            lysItems: [],           // 布局方案列表
            labelKeys: [],          // 标签键列
            labelNames:[],          // 标签名称
            rules: {
                name: [ { required: true, message: '请输入标识', trigger: 'blur' }, { validator: this.checkname, trigger: 'blur' } ],
                title: [ { required: true, message: '请输入标题', trigger: 'blur' }, { validator: this.checkTitle, trigger: 'blur' }],
                lysGuid: [ { required: true, message: '请选择布局方案', trigger: 'blur' } ],
                desc: [ { validator: this.checkDesc, trigger: 'blur' } ]
            },
            updateFlag:-1
        }
    },
    watch: {
        labelNames: function(newNames,oldNames) {
            if (newNames.length < oldNames.length) {
                for (let i = 0; i < oldNames.length; i++) {
                    if (newNames.indexOf(oldNames[i]) == -1) {
                        //删除的labelid
                        let removelabelId = this.labelKeys[i];
                        //取消树形选中
                        let labelNode = this.$refs.applabelTree.setChecked(removelabelId, false, true);

                        if (newNames.length == 1) {
                            this.labelKeys = [];
                        }
                    }
                }
            }
        },
        folderItem: {
            handler (val,old) {
                if (val && this.updateFlag >= 0 ) {
                    this.updateFlag ++ ;
                }

            },
            deep: true
        },
        updateFlag(newValue){
            this.$emit("modify",newValue >=2);
        },
        currNodeId:{
            handler(newNodeId){
                this.initModifyFolderItem(newNodeId);
            },
            immediate: true
        }
    },
    methods: {
        // 创建域、应用系统项模板
        createTemplete: function(category, type) {
            let folderItem = {};
            folderItem.guid = "";
            folderItem.name = "";
            folderItem.title = "";
            folderItem.desc = "";
            folderItem.parent = "";
            folderItem.lysGuid = "";
            folderItem.labels = [];
            folderItem.type = type;
            folderItem.empty = "";
            folderItem.category = category;
            this.folderItem = folderItem;
        },
        // 初始化修改域、应用系统项
        initModifyFolderItem: function(currNodeId) {
            this.updateFlag = -1
            this.resetForm();
            this.createTemplete("", "");
            this.initQueryLysItems();
            this.initQueryLabelTree(currNodeId);
            // this.initQueryFolderItem(currNodeId); // 放到initQueryLabelTree里做最后查询。
        },
        // 初始化查询布局方案
        initQueryLysItems: function() {
            layoutApi.getAllLayoutScheme({}).then((result) => {
                this.lysItems = result;
                if (this.lysItems.length > 0) {
                    this.updateFlag = -1
                    this.folderItem.lysGuid = this.lysItems[0].guid;
                }
            });
        },
        // 初始化查询标签树形
        initQueryLabelTree: function(currNodeId) {
            folderApi.queryLabelTree({}).then((result) => {
                this.labelTree = result;
            }).then( () => { // 初始化标签树后，再初始化标签输入框。
                // this.updateLabelNames();
            }).then( () => { // 最后查询表单项，避免异步请求造成标签输入不展示
                if(currNodeId) {
                    this.initQueryFolderItem(currNodeId).then(()=>{
                        this.updateFlag = 1
                    })
                }
            });
        },
        // 初始化查询域、应用系统项
        initQueryFolderItem: function(currNodeId) {
            return new Promise((resolve)=>{
                folderApi.queryFolderItem({ "folderGuid": currNodeId }).then((result) => {
                    this.updateFlag = -1
                    this.folderItem = result;
                    this.folderItem.empty = "";
                    resolve()
                })
            })

        },
        // 重置表单
        resetForm: function() {
            // this.$refs["folderItem"].resetFields();
            this.labelTree = []
        },
        // 下拉选择处理空值
        tagSelectChange: function() {
            if (this.labelNames == "") {
                this.labelNames = [];
            }
        },
        // 标签树切换选中事件
        handleCheckChange : function (data, checked, chldChecked) {
            // 获取选中节点的父节点
            var checkedParentNodes = this.getParentCheckedNodes(this.$refs.applabelTree.store)
            // 显示选中父标签名称
            this.labelNames = []
            this.labelKeys = [];
            for(var i in checkedParentNodes) {
                var labelItem = checkedParentNodes[i]
                this.labelNames.push(labelItem.label)
                this.labelKeys.push(labelItem.id);
            }
            // 获取所有选中的标签
            var checkedNodes = this.$refs.applabelTree.getCheckedNodes(false, false)
            // 所有选中节点ID存到 folderItem 属性
            this.folderItem.labels = []
            for(var i in checkedNodes) {
                var labelItem = checkedNodes[i]
                this.folderItem.labels.push(labelItem.id)
            }
        },
        // 编辑时，更新labelNames
        updateLabelNames: function() {
            // 获取选中节点的父节点
            console.log(this.$refs.applabelTree)
            var checkedParentNodes = this.getParentCheckedNodes(this.$refs.applabelTree.store)
            // 显示选中父标签名称
            this.labelNames = []
            this.labelKeys = [];
            for(var i in checkedParentNodes) {
                var labelItem = checkedParentNodes[i]
                this.labelNames.push(labelItem.label)
                this.labelKeys.push(labelItem.id)
            }
        },
        // 获取选中节点的父节点
        getParentCheckedNodes: function(store) {
            const checkedNodes = [];
            const traverse = function(node) {
                const childNodes = node.root ? node.root.childNodes : node.childNodes;

                childNodes.forEach(child => {
                    if (child.checked) {
                        checkedNodes.push(child.data);
                    }
                    if (child.indeterminate) {
                        traverse(child);
                    }
                });
            };
            traverse(store)
            return checkedNodes;
        },
        // 标识输入后转成大写
        // onChangeName: function(value) {
        //     this.folderItem.name = this.folderItem.name.toUpperCase();
        // },
        // 验证标识是否重复
        checkname : function(rule, value, callback) {
            this.folderItem.name = this.folderItem.name.toUpperCase()
            if(value.length > 30){
                callback(new Error('标识长度不能超过30个字符'));
            }else if(!/^[a-zA-Z]\w{0,49}$/.test(value)){
                callback(new Error('标识由字母、数字和_组成,并且以字母开头'));
            }else{

                let datas = { "datas": JSON.stringify(this.folderItem) };
                folderApi.checkFolderName(datas).then(res =>{
                    if(res.hassame){
                        callback(new Error('标识不能重复'));
                    }else{
                        callback();
                    }
                }).catch(error => {
                    console.log(error);
                });
            }
        },
        // 验证标题
        checkTitle: function(rule, value, callback) {
            if (value.length > 30) {
                callback(new Error('标题长度不能超过30个字符'));
            } else if (/\.$/.test(value)) {
                callback(new Error('标题不能以.结尾'))
            } else if (/[/\\*<>"'\\|?:]/.test(value)) {
                callback(new Error('标题不能包含\\ 、/ 、: 、* 、? 、" 、\' 、< 、> 、|中任意字符'))
            } else {
                let datas = { "datas": JSON.stringify(this.folderItem) };
                folderApi.checkFolderTitle(datas).then(res =>{
                    if(res.hassame){
                        callback(new Error('标题不能重复'));
                    }else{
                        callback();
                    }
                }).catch(error => {
                    console.log(error);
                });
                // callback();
            }
        },
        // 验证说明
        checkDesc: function(rule, value, callback) {
            if (value != "") {
                if (/^.*[<|>].*$/.test(value)) {
                    callback(new Error('说明不能包含特殊字符< | >'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        },
        // 确认操作返回结果
        saveDomain: function() {
            return new Promise((resolve)=>{
                this.folderItem.name = this.folderItem.name.toUpperCase()
                this.$refs["folderItem"].validate((valid) => {
                    if (valid) {
                        this.updateFlag = -1
                        this.folderItem.labels = this.$refs.applabelTree.getCheckedKeys();
                        let datas = { "datas": JSON.stringify(this.folderItem) };

                        folderApi.saveFolderItem(datas).then((result) => {
                            this.updateFlag = 1
                            this.$emit("save",result)
                            resolve(result)
                        }).catch((error) => {
                            this.$emit("save",false)
                            resolve(false)
                        });
                    } else {
                        this.$emit("save",false)
                        resolve(false)
                    }
                });
            })
        }
    }
}
</script>

<style scoped>
.tag-tree >>> .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #FFF;
    border-color: #E5E5E5;
}
.input-toupper >>> .el-input__inner {
    text-transform: uppercase;
}
#irp-domain .el-divider--horizontal{
    margin: 5px 0px;
}
</style>

<style>
/* 布局方案下拉框面板高度 */
.irp-domain_lys-popper,
.irp-domain_lys-popper .el-scrollbar__wrap {
    height: 210px;
}

/* 标签下拉框面板高度 */
.irp-domain_labels-popper,
.irp-domain_labels-popper .el-scrollbar__wrap {
    height: 150px;
}

/* 多选select下拉框，回显框最大显示高度 */
#irp-domain .el-select__tags {
    max-height: 150px;
    overflow: auto;
}
</style>
